package ar.edu.itba.twiteros.servlet;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import twitter4j.Twitter;
import twitter4j.TwitterException;
import ar.edu.itba.twiteros.util.GrantTwitterAccess;

@SuppressWarnings("serial")
public class SendServlet extends HttpServlet{

	private static int MAX_LENGHT=40;
	
	@Override
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {

		
	}
	
	@Override
	public void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		RequestDispatcher dispatcher= getServletContext().getRequestDispatcher("/index");
		
		Long uid= Long.valueOf(req.getParameter("fb_sig_user"));
		Twitter twitter = new Twitter();
		GrantTwitterAccess grantAccess= new GrantTwitterAccess(twitter, uid);
		
		
		if(grantAccess.setAccessToken())
		{
			String msg= req.getParameter("message");
			if(msg.length()<=MAX_LENGHT){
				try {
					twitter.updateStatus(msg);
				} catch (TwitterException e) {
					req.setAttribute("error_message", e.getMessage());
					dispatcher= getServletContext().getRequestDispatcher("/error.jsp");
					dispatcher.forward(req, resp);
				}
			}
		}
		
		dispatcher.forward(req, resp);
	}
}
